package com.gs.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import android.view.Menu;
import android.view.MenuItem;

import com.gs.R;

public class OptionMenu {

	public static final String OPT_ADMIN = "Admin";
	public static final String OPT_OPTIONS = "Options";
	public static final String OPT_RIEPILOGO = "Riepilogo";
	public static final String OPT_ADD_USCITE = "Nuova Uscita";
	public static final String OPT_ADD_ENTRATE = "Nuova Entrata";
	private static final int DEFAULT_IMAGE_RES = R.drawable.soldi;
	private Menu menu;
	private ArrayList<Integer> order = new ArrayList<Integer>();
	private HashMap<String, Integer> items = new HashMap<String, Integer>();

	public OptionMenu(final Menu menu) {
		if (menu != null) {
			this.menu = menu;
		}
		inserisciOptionsStandard();
	}

	private void inserisciOptionsStandard() {
		inserisciOption(OPT_ADMIN);
		inserisciOption(OPT_OPTIONS);
		inserisciOption(OPT_RIEPILOGO);
		inserisciOption(OPT_ADD_ENTRATE);
		inserisciOption(OPT_ADD_USCITE);
	}

	public void inserisciOption(final String title, final int resImage, final int itemId) {
		addOrderList(itemId, -1);
		MenuItem newItem = menu.add(Menu.NONE, itemId, order.size() - 1, title);
		newItem.setIcon(resImage);
	}

	private void addOrderList(final int itemId, final int position) {
		Integer itemid = new Integer(itemId);
		if (position == -1) {
			order.add(itemid);
		} else {
			order.add(position, itemid);
		}
	}

	public void inserisciOption(final String title, final int resImage, final int itemId, final int order) {
		addOrderList(itemId, order);
		MenuItem newItem = menu.add(Menu.NONE, itemId, order, title);
		newItem.setIcon(resImage);
	}

	public void inserisciOption(final String title) {
		inserisciOption(title, DEFAULT_IMAGE_RES);
	}

	public void inserisciOption(final String title, final int resImage) {
		int itemId = creaItemId(title);
		addOrderList(itemId, -1);
		inserisciOption(title, resImage, itemId, order.size() - 1);
	}

	public int getItem(final String title) {
		Integer itemInteger = items.get(title);
		if (itemInteger != null) {
			return itemInteger.intValue();
		}
		return -1;
	}

	private int creaItemId(final String title) {

		int max = 0;
		Iterator<Integer> valori = items.values().iterator();

		while (valori.hasNext()) {
			Integer next = valori.next();
			if (next.intValue() > max) {
				max = next.intValue();
			}
		}

		int newItem = max + 1;
		items.put(title, new Integer(newItem));

		return newItem;
	}

	public Menu getMenu() {
		return menu;
	}

	public void setMenu(final Menu menu) {
		this.menu = menu;
	}
}
